#include "game.h"
#include "background.h"
#include"menu.h"
#include <QApplication>
#include <QGraphicsScene>
#include <QTimer>
#include <QKeyEvent>
#include <QLabel>
#include <QRandomGenerator>
#include <QPropertyAnimation>
Game::Game(QWidget* parent) : QGraphicsView(parent) {
    // 初始化场景
    setFixedSize(800, 600);
    // 先创建菜单
    gameMenu = new Menu(this);
    setScene(gameMenu);
    isGameStarted = false;

    connect(gameMenu, &Menu::startGame, this, &Game::startGame);
    connect(gameMenu, &Menu::exitGame, qApp, &QApplication::quit);


}





void Game::startGame() {
    // 初始化游戏场景
    scene = new QGraphicsScene(0, 0, width(), height());
    setScene(scene);
    isGameStarted = true;
    player=new Player();
    player->setPos(100,scene->height()-player->pixmap().height()-30);
    //qDebug() << "setPos完成";
    scene->addItem(player);

    // 调试输出
    qDebug() << "Game reset. Player position: " << player->pos() ;

    physicsTimer.setInterval(16);
    connect(&physicsTimer, &QTimer::timeout, [this](){
        player->updatePhysics();
    });
    physicsTimer.start();

    // 分数显示
    scoreLabel = new QLabel("Score:0",this);
    scoreLabel->setGeometry(10, 10, 200, 50);
    scoreLabel->setStyleSheet("font: bold 18px 'Arial'; color: #ECF0F1;");
    scoreLabel->setText("Score: 0");
    scoreLabel->show();
    scoreLabel->raise(); // 确保在最上层
    // 初始化定时器
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Game::updateGame);
    timer->start(30); // 主循环30ms刷新


    spawnTimer = new QTimer(this);
    connect(spawnTimer, &QTimer::timeout, this, &Game::spawnObstacle);
    spawnTimer->start(3000); // 障碍物2秒生成

    jellyfishTimer = new QTimer(this);
    connect(jellyfishTimer, &QTimer::timeout, this, &Game::spawnJellyfish);
    jellyfishTimer->start(600); // 每1秒生成一个水母



    // 游戏状态初始化
    score = 0;
    gameOver = false;
    bg1=new Background(":/images/background.png", 10.0);
    bg2=new Background(":/images/background.png", 10.0);
    bg1->setZValue(-10);
    bg2->setZValue(-10)  ;  // 确保在最底层
    bg1->setPos(0, 0);
    bg2->setPos(bg1->pixmap().width() - 5, 0); // 轻微重叠

    bg1->isLeading = true;

    // 添加到场景
    scene->addItem(bg1);
    scene->addItem(bg2);
}




void Game::keyPressEvent(QKeyEvent* event) {
    if(!isGameStarted) return;
    if (event->key() == Qt::Key_Space && !gameOver) {
        player->jump();
    }
    if(event->key()==Qt::Key_F&&!gameOver){
        player->crouch();
    }


}

void Game::spawnObstacle() {
    if (gameOver) return;

    //随机产生障碍物类型
    int randomType=QRandomGenerator::global()->bounded(4);
    if(randomType==3){
        return;
    }
    ObstacleType type;
    switch(randomType){
    case 0:
        type=OBSTACLE_1;
        break;
    case 1:
        type=OBSTACLE_2;
        break;
    case 2:
        type=OBSTACLE_3;
        break;
    }

    // 创建图片障碍物对象
    Obstacle* obstacle = new Obstacle(type);

    if(type==OBSTACLE_1||type==OBSTACLE_2){
        obstacle->setPos(
            scene->width(),
            scene->height() - obstacle->pixmap().height() - 40
            );

    }
    else if(type==OBSTACLE_3){
        obstacle->setPos(
            scene->width(),
            scene->height()/2-200
        );
    }



    scene->addItem(obstacle);
    obstacles.append(obstacle);


}
void Game::spawnJellyfish() {
    Jellyfish* jellyfish = new Jellyfish();
    QPixmap jellyImg(":/images/jellyfish.png");

    // 设置生成区域（中下部）
    const int minY =JELLYFISH_AREA.height() * 1/4;
    const int maxY = JELLYFISH_AREA.height()*4/5  - jellyImg.height();

    jellyfish->setPixmap(jellyImg);
    jellyfish->setPos(
        JELLYFISH_AREA.width(), // 从右侧外生成
        QRandomGenerator::global()->bounded(minY, maxY)
        );

    scene->addItem(jellyfish);
    jellyfishList.append(jellyfish);
}

void Game::updateGame() {
    if (gameOver) return;

        // 更新背景位置
    if(bg1->isLeading) {
        bg1->updatePosition(bg2);
        bg2->updatePosition(bg1);
    } else {
        bg2->updatePosition(bg1);
        bg1->updatePosition(bg2);
    }

    // 移动障碍物
    for (auto obstacle : obstacles) {
        obstacle->move();
    }
    for (auto jellyfish : jellyfishList) {
        jellyfish->setX(jellyfish->x() - bg1->speed()); // 比背景稍慢
    }

    // 碰撞检测
     checkCollisions();

     // 清理对象
     cleanObstacles();
     cleanJellyfish();
     updateScoreDisplay();
    }


void Game::checkCollisions() {
    // 障碍物碰撞
    for (auto obstacle : obstacles) {
        if (player->collidesWithItem(obstacle)) {
            gameOver = true;
            QTimer::singleShot(0, this, [this](){
                timer->stop();
                spawnTimer->stop();
                jellyfishTimer->stop();
                physicsTimer.stop();
                showGameOverDialog();
            });
            // scoreLabel->setText("Game Over! Score: " + QString::number(score / 10) + "\nPress R to restart");
            return;
        }
    }
    // 水母碰撞
    for (auto jellyfish : jellyfishList) {
        // if (player->collidesWithItem(jellyfish)) {
        //     score += 10; // 每捕捉一个水母加10分
        //     updateScoreDisplay();
        //     scene->removeItem(jellyfish);
        //     jellyfishList.removeAll(jellyfish);
        //     delete jellyfish;
        // }
        QMutableListIterator<Jellyfish*> jIt(jellyfishList);
        while (jIt.hasNext()) {
            Jellyfish* jellyfish = jIt.next();
            if (player->collidesWithItem(jellyfish)) {
                score += 1;
                scene->removeItem(jellyfish);
                jIt.remove();
                delete jellyfish;
            }
        }
    }
}

// void Game::updateScoreDisplay() {
//     if (QLabel* label = findChild<QLabel*>()) {
//         label->setText(QString("Score: %1").arg(score));
//     }
//
void Game::updateScoreDisplay() {
    scoreLabel->setText(QString("Score: %1").arg(score));
    scoreLabel->adjustSize(); // 自动调整标签大小
}

void Game::cleanObstacles() {
    QMutableListIterator<Obstacle*> i(obstacles);
    while (i.hasNext()) {
        auto obstacle = i.next();
        if (obstacle->isOutOfScreen()) {
            scene->removeItem(obstacle);
            i.remove();
            delete obstacle;
        }
    }
}

void Game::cleanJellyfish() {
    // QMutableListIterator i(jellyfishList);
    // while (i.hasNext()) {
    //     auto jellyfish = i.next();
    //     if (jellyfish->isOutOfScene()) {
    //         scene->removeItem(jellyfish);
    //         i.remove();
    //         delete jellyfish;
    //     }
    // }
    // QMutableListIterator<Jellyfish*> jIt(jellyfishList);
    // while (jIt.hasNext()) {
    //     Jellyfish* jellyfish = jIt.next();
    //     if (jellyfish->x() + jellyfish->boundingRect().width() < 0) {
    //         scene->removeItem(jellyfish);
    //         jIt.remove();
    //         delete jellyfish;
    //     }
    // }
    QMutableListIterator<Jellyfish*> jIt(jellyfishList);
    while (jIt.hasNext()) {
        Jellyfish* jellyfish = jIt.next();
        if (player->collidesWithItem(jellyfish)) {
            score += 1;  // 按需求改为加1分或保持原逻辑
            updateScoreDisplay();
            scene->removeItem(jellyfish);
            jIt.remove();
            delete jellyfish;
        }
    }
}

void Game::resetGame() {
    // 清理所有对象
    scene->clear();
    obstacles.clear();
    jellyfishList.clear();
    // 重新初始化玩家
    player = new Player();
    player->setPos(100, scene->height() - 200);
    scene->addItem(player);

    // 重置状态
    score = 0;
    gameOver = false;
    scoreLabel->setText("Score: 0");

    // 停止并重新启动物理定时器
    physicsTimer.stop();
    connect(&physicsTimer, &QTimer::timeout, [this]() {
        player->updatePhysics();  // 确保跳跃状态正确更新
    });
    physicsTimer.start();
}

void Game::showMenu() {
    // 停止并清理当前游戏定时器
    physicsTimer.stop();
    spawnTimer->stop();
    jellyfishTimer->stop();
    timer->stop();
    // 清理当前场景
    if (scene != nullptr) {
        scene->clear();
        delete scene;
        scene = nullptr;
    }
    // 显示菜单场景
    setScene(gameMenu);
    isGameStarted = false;
}

// void Game::startGame() {
//     // 初始化游戏场景
//     scene = new QGraphicsScene(0, 0, width(), height());
//     setScene(scene);
//     isGameStarted = true;
//     // 初始化玩家和背景等
// }
void Game::showGameOverDialog() {
    QMessageBox gameOverMsg(this);
    gameOverMsg.setWindowTitle("游戏结束");
    gameOverMsg.setText(QString("游戏结束！\n最终分数: %1").arg(score));

    // 添加重启按钮
    QPushButton* quitButton = gameOverMsg.addButton("退出游戏", QMessageBox::ActionRole);
    //QPushButton* menuButton = gameOverMsg.addButton("返回菜单", QMessageBox::ActionRole);

    gameOverMsg.exec();

    if (gameOverMsg.clickedButton() == quitButton) {
        QApplication::quit();
        // resetGame();
        // startGame();
    }/* else if (gameOverMsg.clickedButton() == menuButton) {
        resetGame();
        showMenu();
    }*/
}
